package com.dff.jrfw.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.dff.jrfw.R;
import com.dff.jrfw.utils.ToastUtil;

import java.util.concurrent.atomic.AtomicBoolean;

public class UpdateDialog extends Dialog {
    private final MutableLiveData<Integer> progress;
    private final AtomicBoolean downloadFlag;
    private long lastClick = 0;

    public UpdateDialog(@NonNull Context context, MutableLiveData<Integer> progress, AtomicBoolean downloadFlag) {
        super(context, R.style.CustomDialog);
        this.progress = progress;
        this.downloadFlag = downloadFlag;
        setCanceledOnTouchOutside(false);   // 点击其他地方dialog不消失
        setCancelable(false);         // 点击返回键dialog不消失
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pop_updata);
        ProgressBar pb = findViewById(R.id.pb);
        TextView tvProgress = findViewById(R.id.tv_progress);
        Observer<Integer> observer = integer -> {
            tvProgress.setText(format(integer));
            pb.setProgress(integer);
        };
        findViewById(R.id.tv_sure).setOnClickListener(v -> {
            long now = System.currentTimeMillis();
            if (now - lastClick > 1000) {
                ToastUtil.toast("再次点击取消更新");
                lastClick = now;
            } else {
                downloadFlag.set(false);
            }
        });
        progress.observeForever(observer);
        setOnDismissListener(dialog -> {
            if (!downloadFlag.get()) {
                ToastUtil.toast("取消更新");
            }
            progress.removeObserver(observer);
        });
    }

    @SuppressLint("InvalidWakeLockTag")
    @Override
    public void show() {
        super.show();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void dismiss() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.dismiss();
    }

    private String format(int p) {
        int i = p % 100;
        return p / 100 +
                (i < 10 ? ".0" : ".") +
                i +
                "%";
    }

}
